An associative array, where arbitrary keys are mapped to values.
{}
{'a':1, 'b':2, 'c':3}
{1:'a', 2:'b', 3:'c'} # keys don't have to be strings
{1:'a', '2':'b', 3:'c'} # keys don't even need to be the same class
dict()
dict(a=1, b=2, c=3)# using the fromkeys method
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dict.fromkeys(x, y)
# using dict comprehension
keys = ['a', 'b', 'c']
values = [1, 2, 3]
{key: value for key, value in zip(keys, values)}# using the update method
x.update(y)
# using the unpacking operator
{**x, **y}mydict = {'a':1, 'b':2, 'c':3}
'b' in mydict
# Truemydict = {'a':1, 'b':2, 'c':3}
mydict[0] # fails
mydict['a']
mydict['d'] = 4
mydict['d'] = None # doesn't remove the key| method | description |
|---|---|
.clear() |
remove all items (in-place) |
.copy() |
shallow copy |
.fromkeys(keys, values) |
create from keys and values |
.get(key, default) |
return the value for key if key is in the dictionary, else default |
.items() |
get a list of (key, value) tuples |
.keys() |
get a list of keys |
.pop(key) |
remove key (in-place) |
.popitem() |
remove the item that was last inserted |
.setdefault(key, default) |
return the value if key exists, otherwise insert and return the default |
.update(items) |
append new items |
.values() |
get a list of values |
# return a list of keys in order
# keys need to be the same class for this to work
sorted(mydict) Transform values
def multiply_items_by_two(item):
return (item[0], item[1] * 2)
mydict = dict(a=1, b=2, c=3)
dict(map(multiply_items_by_two, mydict.items()))
# {'a': 2, 'b': 4, 'c': 6}Filter values
def multiply_items_by_two(item):
return (item[0], item[1] * 2)
mydict = dict(a=1, b=2, c=3)
dict(map(multiply_items_by_two, mydict.items()))
# {'a': 2, 'b': 4, 'c': 6}# implicitly loop over keys
for key in mydict:
print(key)
# explicitly loop over keys
for key in mydict.keys():
print(key)for value in mydict.values():
print(value)# loop over items as tuples
for item in mydict.items():
print(item)
print(item[0]) # key
print(item[1]) # value
# loop over unpacked items
for key, value in mydict.items():
print(key)
print(value)from pprint import pprint
pprint(dir(dict))
# ['__class__',
# '__contains__',
# '__delattr__',
# '__delitem__',
# '__dir__',
# '__doc__',
# '__eq__',
# '__format__',
# '__ge__',
# '__getattribute__',
# '__getitem__',
# '__gt__',
# '__hash__',
# '__init__',
# '__init_subclass__',
# '__iter__',
# '__le__',
# '__len__',
# '__lt__',
# '__ne__',
# '__new__',
# '__reduce__',
# '__reduce_ex__',
# '__repr__',
# '__reversed__',
# '__setattr__',
# '__setitem__',
# '__sizeof__',
# '__str__',
# '__subclasshook__',
# 'clear',
# 'copy',
# 'fromkeys',
# 'get',
# 'items',
# 'keys',
# 'pop',
# 'popitem',
# 'setdefault',
# 'update',
# 'values']